package servlet.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import pojo.User;
import service.OrderService;
import service.UserLoginService;
import until.SnowFlakeUUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@WebServlet("/gobuy")
public class GoBuy extends HttpServlet {
    private SnowFlakeUUID snowFlakeUUID = new SnowFlakeUUID();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        // 获取请求体中的 JSON 数据
        BufferedReader reader = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String jsonStr = sb.toString();
        // 使用 FastJSON 解析 JSON 数据
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        // 提取用户名
        String username = jsonObject.getString("username");
        // 提取购买信息数组
        JSONArray purchasesArray = jsonObject.getJSONArray("purchases");
        // 获取purchasesArray的大小
        int purchasesArraySize = purchasesArray.size();
        if (purchasesArraySize==0){
            // 返回响应
            JSONObject responseObj = new JSONObject();
            responseObj.put("success", false);
            resp.getWriter().write(responseObj.toJSONString());
            return;
        }
        //总数量
        int totalCount = 0;
        //总价格
        double totalAmount = 0.0;
        long orderId = snowFlakeUUID.replace();
        OrderService orderService = new OrderService();
        int count = 0;
        for (Object obj : purchasesArray) {
            count+=1;
            long orderItemId = snowFlakeUUID.replace();
            JSONObject purchaseObj = (JSONObject) obj;
            // 提取购买信息
            //购物车IDid
            String id = purchaseObj.getString("id");
            //图书名字
            String name = purchaseObj.getString("name");
            //图书价格
            double price = purchaseObj.getDoubleValue("price");
            //图书数量
            int quantity = purchaseObj.getIntValue("quantity");
            String bookID = purchaseObj.getString("bookId");
            totalCount += quantity;
            totalAmount +=price;
            // 进行后续操作，例如保存购买信息到数据库
            System.out.println("插入第"+count+"订单项中,请稍等:"+LocalDateTime.now());
            int i = orderService.insertOrderItem(orderItemId, orderId, Long.parseLong(bookID), quantity,name,price);
            System.out.println("插入第"+count+"订单项完成:"+LocalDateTime.now());
            if (i==1){
                System.out.println("执行插入订单项操作:订单项表插入成功");
            }
        }
        //存入order表
        int y = insertOrder(orderId,username,totalCount,totalAmount);
        if (y==1){
            // 返回响应
            JSONObject responseObj = new JSONObject();
            responseObj.put("success", true);
            System.out.println("开始响应");
            resp.getWriter().write(responseObj.toJSONString());
        }else {
            // 返回响应
            JSONObject responseObj = new JSONObject();
            responseObj.put("success", false);
            resp.getWriter().write(responseObj.toJSONString());
        }


    }

    //存入order表
    private int insertOrder(long orderId,String username, int totalCount, double totalAmount) {

        UserLoginService userLoginService = new UserLoginService();
        User user = userLoginService.searchUserId(username);
        Long id = user.getId();
        OrderService orderService = new OrderService();
        System.out.println("插入订单中:"+LocalDateTime.now());
        int i = orderService.insertOrder(orderId, user.getId(), totalCount, totalAmount);
        if (i==1){
            System.out.println("已生成订单！"+LocalDateTime.now());
            return i;
        }
        return 0;
    }
    //验证是否重复

    //验证是否重复
    public  String ShortUUIDGenerator () {
        UUID uuid = UUID.randomUUID();
        // 获取UUID的字符串表示
        String uuidStr = uuid.toString().replace("-", ""); // 去掉连字符
        // 取UUID字符串的前15位作为15位UUID
        String shortUUID = uuidStr.substring(0, 15);
        // 生成一个8位的随机数字字符串作为订单ID
        return shortUUID;
//        Random random = new Random();
//        StringBuilder orderIdBuilder = new StringBuilder();

//        while (true) {
//            for (int i = 0; i < 8; i++) {
//                orderIdBuilder.append(random.nextInt(10)); // 生成0到9之间的随机数字
//            }
//
//            String orderId = orderIdBuilder.toString();
//            if (orderId(Long.parseLong(orderId))) {
//                return orderId;
//            } else {
//                orderIdBuilder.setLength(0); // 清空 StringBuilder
//            }
//        }
//        for (int i = 0; i < 8; i++) {
//            orderIdBuilder.append(random.nextInt(10)); // 生成0到9之间的随机数字
//        }
//
//        String orderId = orderIdBuilder.toString();
//        return orderId;
        //验证是否重复
    }
    private String generateOrderItemId() {
        // 实现订单项ID的生成逻辑
        Random random = new Random();
        StringBuilder orderIdBuilder = new StringBuilder();

//        while (true) {
//            for (int i = 0; i < 8; i++) {
//                orderIdBuilder.append(random.nextInt(10)); // 生成0到9之间的随机数字
//            }
//
//            String orderId = orderIdBuilder.toString();
//            if (orderItemId(Long.parseLong(orderId))) {
//                return orderId;
//            } else {
//                orderIdBuilder.setLength(0); // 清空 StringBuilder
//            }
//        }
        for (int i = 0; i < 8; i++) {
            orderIdBuilder.append(random.nextInt(10)); // 生成0到9之间的随机数字
        }
        String orderId = orderIdBuilder.toString();
        return orderId;
    }
}
